//
//  LKElearningAvPlayerViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/8.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKElearningAvPlayerViewController.h"
#import "LKAvPlayerHeaderCell.h"
#import "LKAvPlayerMiddleCell.h"
#import "LKAvPlayerBottomCell.h"
#import "LXPlayModel.h"
#import "LXAVPlayView.h"
#import "LLKCollectionManage.h"
@interface LKElearningAvPlayerViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)LKBaseTableview *tableview;
@property (nonatomic, strong) NSMutableArray *playInfos;
@property(nonatomic,strong)LXAVPlayView *playerview;
@property(nonatomic,strong)UIView *avBgView;
@property(nonatomic,strong)UIView *bottomeButtonView;
@property(nonatomic,strong)UILabel *playCountLabel;
@property(nonatomic,strong)UIButton *collectBtn;
@property(nonatomic,strong)UIButton *priseBtn;

@end

@implementation LKElearningAvPlayerViewController

-(RACSubject *)pushSubject{
    if (!_pushSubject) {
        _pushSubject = [[RACSubject alloc] init];
    }
    return _pushSubject;
}

-(void)setUpTableview{
    self.avBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 330)];
    [self.view addSubview:self.avBgView];
    [self setPlayCountViewAndPriseAndCollectionViewWithView:self.avBgView];
    _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 400, WIDTH, HEIGHT - 400) style:UITableViewStyleGrouped registercellClasss:@[@"LKAvPlayerHeaderCell",@"LKAvPlayerMiddleCell",@"LKAvPlayerBottomCell"]];
    [self.view addSubview:_tableview];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.backgroundColor = cellHeaderBgColor;
    _tableview.estimatedRowHeight = 200;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTableview];
    [self setUpAvplayerInview:self.avBgView];
    [self getVideoDetailInformation];
    [self videoPlayCountAdd];
//    self.tableview.estimatedRowHeight = 200;
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.backButton.hidden = YES;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    CGFloat offset = 0;
//    [self.navigationController.navigationBar
//     setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:201/255.0 blue:31/255.0 alpha:(offset / 64)>0.99?0.99:(offset / 64)]] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar
//     setShadowImage:[UIImage new]];
    
}
-(UIImage*)imageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.shadowImage = nil;
    [self.playerview destroyPlayer];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        LKAvPlayerMiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKAvPlayerMiddleCell"];
        cell.model = self.videoModel;
        return cell;
    }
    LKAvPlayerBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKAvPlayerBottomCell"];
    [cell.prictiseBtn addTarget:self action:@selector(startPricticeAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.model = self.videoModel;
    return cell;
    
}

/**
 开始联系
 */
-(void)startPricticeAction:(UIButton *)btn{
    LKVideoExaminationModel *model = self.videoModel.videoExamination[0];
    NSLog(@"测试卷ID%@",model.examinationPaperId);
    [self.pushSubject sendNext:model.examinationPaperId];
    [self dismissViewControllerAnimated:NO completion:nil];
}
/**
 返回点击事件

 */
-(void)backVideoPage:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return UITableViewAutomaticDimension;
    }
    return 204;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.000000000001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == 1 ? 0.0000000001:12;
}
-(void)setUpAvplayerInview:(UIView *)view{
    LXPlayModel *model =[[LXPlayModel alloc]init];
//    model.playUrl = @"http://hc34.aipai.com/user/128/31977128/6009407/card/44044719/card.mp4?l=f";
    model.playUrl = [NSString stringWithFormat:@"%@%@",ServerlUrl,_videoModel.videoUrl];
    model.videoTitle = self.videoModel.videoName;
    model.fatherView = view;
    self.playerview =[[LXAVPlayView alloc]init];
    self.playerview.isLandScape = YES;
    self.playerview.isAutoReplay = NO;
    self.playerview.currentModel = model;
    WS(weakSelf);
    self.playerview.backBlock = ^{
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.3];
        [animation setType:kCATransitionPush];
        [animation setSubtype:kCATransitionFromLeft];
        [[[[UIApplication sharedApplication] keyWindow] layer] addAnimation:animation forKey:nil];
        NSLog(@"点击了");
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    };
}
-(BOOL)shouldAutorotate{
    return YES;
}
// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault; // your own style
}

/**
 获取视频的详细信息
 */
-(void)getVideoDetailInformation{
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:VideoDetailUrl header:[LKUserInforTool header] parameters:@{@"Id":self.videoModel.videoId} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        self.videoModel = [LKVideoModel modelWithDictionary:responseObject[@"result"]];
        self.playCountLabel.text = [NSString stringWithFormat:@"%@次播放",self.videoModel.playCount];
        if ([self.videoModel.isCollectioned integerValue]) {
            self.collectBtn.selected = YES;
        }else{
            self.collectBtn.selected = NO;
        }
        self.priseBtn.selected = NO;
        self.videoModel.collectionCount = self.collectNumber;
        BOOL isexit = [[LLKCollectionManage shareManager] APPIsExist:self.videoModel];
        if (isexit) {
            
            [[LLKCollectionManage shareManager] deleteByUserID:self.videoModel.videoId];
            [[LLKCollectionManage shareManager] addCollect:self.videoModel];
            
        }else{
            [[LLKCollectionManage shareManager] addCollect:self.videoModel];
        }
        LKVideoExaminationModel *model = self.videoModel.videoExamination[0];
        NSLog(@"测试卷ID%@",model.examinationPaperId);
        [self.tableview reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 设置视频下方播放次数和收藏以及点赞的功能
 */
-(void)setPlayCountViewAndPriseAndCollectionViewWithView:(UIView *)fatherView{
    self.bottomeButtonView = [[UIView alloc] init];
    self.bottomeButtonView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomeButtonView];
    [self.bottomeButtonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(fatherView.mas_bottom).offset(0);
        make.height.mas_equalTo(60);
    }];
    self.playCountLabel = [[UILabel alloc] init];
    self.playCountLabel.text = @"12";
    self.playCountLabel.textColor = COLOR_HEX(0x929292);
    self.playCountLabel.font = [UIFont systemFontOfSize:15];
    [self.bottomeButtonView addSubview:self.playCountLabel];
    [self.playCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomeButtonView.mas_left).offset(16);
        make.centerY.equalTo(self.bottomeButtonView.mas_centerY);
    }];
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.collectBtn setTitle:@"收藏" forState:UIControlStateNormal];
    [self.collectBtn setTitle:@"收藏" forState:UIControlStateSelected];
    [self.collectBtn setTitleColor:COLOR_HEX(0x929292) forState:UIControlStateNormal];
    [self.collectBtn setTitleColor:COLOR_HEX(0x929292) forState:UIControlStateSelected];
    [self.collectBtn setImage:[UIImage imageNamed:@"elarningcollect"] forState:UIControlStateNormal];
    [self.collectBtn setImage:[UIImage imageNamed:@"elarningcollcthou"] forState:UIControlStateSelected];
    self.collectBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [self.collectBtn addTarget:self action:@selector(gotoCollectionAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomeButtonView addSubview:self.collectBtn];
    [self.collectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bottomeButtonView.mas_right).offset(-16);
        make.centerY.equalTo(self.bottomeButtonView.mas_centerY);
        make.height.mas_equalTo(60);
    }];
    self.priseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.priseBtn setTitle:@"点赞" forState:UIControlStateNormal];
    [self.priseBtn setTitle:@"点赞" forState:UIControlStateSelected];
    [self.priseBtn setTitleColor:COLOR_HEX(0x929292) forState:UIControlStateNormal];
    [self.priseBtn setTitleColor:COLOR_HEX(0x929292) forState:UIControlStateSelected];
    [self.priseBtn setImage:[UIImage imageNamed:@"elarningzan"] forState:UIControlStateNormal];
    [self.priseBtn setImage:[UIImage imageNamed:@"elarningzanhou"] forState:UIControlStateSelected];
    [self.priseBtn addTarget:self action:@selector(gotoPriseAction:) forControlEvents:UIControlEventTouchUpInside];
    self.priseBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [self.bottomeButtonView addSubview:self.priseBtn];
    [self.priseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.collectBtn.mas_left).offset(-35);
        make.centerY.equalTo(self.bottomeButtonView.mas_centerY);
        make.height.mas_equalTo(60);
    }];
    [self setButtonTitleAndImagePositionWithButton:self.collectBtn];
    [self setButtonTitleAndImagePositionWithButton:self.priseBtn];
}

/**
 收藏的操作

 */
-(void)gotoCollectionAction:(UIButton *)btn{
    if (!btn.selected) {
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:VideoCollectUrl header:[LKUserInforTool header] parameters:@{@"Id":self.videoModel.videoId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            
//            [btn setTitle:[NSString stringWithFormat:@" %ld",[self.model.collectionCount integerValue] + 1] forState:UIControlStateSelected];
            btn.selected = YES;
            [SVProgressHUD showInfoWithStatus:@"收藏成功"];
            
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }else{
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:videoCancelColleUrl header:[LKUserInforTool header] parameters:@{@"Id":self.videoModel.videoId} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
//            btn.titleLabel.text = [NSString stringWithFormat:@" %ld",[self.model.collectionCount integerValue]];
            btn.selected = NO;
            [SVProgressHUD showInfoWithStatus:@"取消收藏成功"];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }

//    btn.selected = !btn.selected;
}

/**
 点赞的操作
 */
-(void)gotoPriseAction:(UIButton *)btn{
    NSString *number;
    if (btn.selected) {
        number = @"1";
    }else{
        number = @"-1";
    }
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:VideoPriseUrl header:[LKUserInforTool header] parameters:@{@"Id":self.videoModel.videoId,@"number":number} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([number isEqual:@"1"]) {
//            [btn setTitle:[NSString stringWithFormat:@" %ld",[self..praiseCount integerValue] + 1] forState:UIControlStateSelected];
            [SVProgressHUD showInfoWithStatus:@"点赞成功"];
//            btn.selected = YES;
        }else{
//            btn.selected = NO;
//            btn.titleLabel.text = [NSString stringWithFormat:@" %ld",[self.model.praiseCount integerValue]];
            [SVProgressHUD showInfoWithStatus:@"取消点赞成功"];
        }
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
    btn.selected = !btn.selected;
}

/**
 视频的播放次数+1
 */
-(void)videoPlayCountAdd{
    NSDictionary *param = @{@"Id":self.videoModel.videoId};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:VideoPlayCountUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/**
 设置button的文字和图片的默认位置

 */
-(void)setButtonTitleAndImagePositionWithButton:(UIButton *)button{
    CGSize titleSize = button.titleLabel.bounds.size;
    CGSize imageSize = button.imageView.bounds.size;
    CGFloat interval = 10.0;
    [button setImageEdgeInsets:UIEdgeInsetsMake(0,0, titleSize.height + interval, -(titleSize.width + interval))];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(imageSize.height + interval, -(imageSize.width + interval), 0, 0)];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
